package com.gin.kotlin.gf2gamecommunity.viewmodel

import androidx.lifecycle.ViewModel
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.response.upload.UploadSignature
import okio.IOException
import retrofit2.await
import java.io.File
import java.time.ZonedDateTime

class UploadViewModel : ViewModel() {
    private var signature: UploadSignature? = null

    /**
     * 上传图片
     * @param file File
     * @return 返回对应的HTML代码
     */
    suspend fun upload(file: File): String {
        val sign = fetchSignature()
        // 上传
        api().upload(sign.host, sign.buildBody(file)).await()
        return sign.fileHtml(file.name)
    }

    /**
     * 获取上传签名
     * @return UploadSignature
     */
    private suspend fun fetchSignature(): UploadSignature {
        val sign = this.signature
        // 签名依然有效时， 继续使用
        if (sign != null && sign.expire.isAfter(ZonedDateTime.now())) {
            return sign
        }
        // 签名为空 或 失效 更新签名
        val data = api().getSignature().await().data ?: throw IOException("签名信息为空")
        this.signature = data
        return data
    }

    private fun api() = App.INSTANCE.api.uploadApi

    companion object {
        private val TAG = UploadViewModel::class.java.simpleName
    }
}